

using System.Diagnostics.CodeAnalysis;
using BootstrapBlazor.Components;
using Identity.Models;
using Microsoft.AspNetCore.Components;
using Identity.Extensions;


namespace Identity.Account.Compoents;

/// <summary>
/// 
/// </summary>
public partial class NavigationTree
{
    [NotNull]
    private List<TreeViewItem<Navigation>>? Items { get; set; }



    [Inject]
    [NotNull]
    private ToastService? ToastService { get; set; }

    /// <summary>
    /// 
    /// </summary>
    [Parameter]
    [EditorRequired]
    [NotNull]
    public List<Navigation>? AllMenus { get; set; }

    /// <summary>
    /// 
    /// </summary>
    [Parameter]
    [EditorRequired]
    [NotNull]
    public List<string>? SelectedMenus { get; set; }

    /// <summary>
    /// 保存按钮回调委托
    /// </summary>
    [Parameter]
    [EditorRequired]
    [NotNull]
    public Func<List<string>, Task<bool>>? OnSave { get; set; }

    [CascadingParameter]
    private Func<Task>? CloseDialogAsync { get; set; }

    /// <summary>
    /// 
    /// </summary>
    protected override void OnInitialized()
    {
        base.OnInitialized();

        Items = AllMenus.ToTreeItemList(SelectedMenus, RenderTreeItem,string.Empty);
    }


    private async Task OnClickClose()
    {
        if (CloseDialogAsync != null)
        {
            await CloseDialogAsync();
        }
    }
    private async Task AddSelectedMenuAndAncestors(TreeViewItem<Navigation> item, List<string> selectedMenus)
    {
        // Add the ID of the current item
        selectedMenus.Add(item.Value.Id);

        // Check if the item has a parent
        if (item.Parent != null)
        {
            // Add the ID of the parent item
            selectedMenus.Add(item.Parent.Value.Id);

            // Recursively add ancestors of the parent item
            await AddSelectedMenuAndAncestors(item.Parent, selectedMenus);
        }
    }
    // private Task OnTreeItemChecked(List<TreeViewItem<Navigation>> items)
    // {
    //     SelectedMenus = items.SelectMany(i =>
    //     {
    //         var ret = new List<string>
    //         {
    //             i.Value.Id
    //         };
    //     if (i.Parent != null)
    //     {
    //         ret.Add(i.Parent.Value.Id);
    //     }

    //         return ret;
    //     }).Distinct().ToList();
    //     return Task.CompletedTask;
    // }

private async Task OnTreeItemChecked(List<TreeViewItem<Navigation>> items)
{
    var selectedMenus = new List<string>();

    foreach (var item in items)
    {
        await AddSelectedMenuAndAncestors(item, selectedMenus);
    }

    SelectedMenus = selectedMenus.Distinct().ToList();
}

    private async Task OnClickSave()
    {
        var ret = await OnSave(SelectedMenus);
        if (ret)
        {
            await OnClickClose();
            await ToastService.Success("分配菜单操作", "操作成功！");

        }
        else
        {
            await ToastService.Error("分配菜单操作", "操作失败，请联系相关管理员！");
        }
    }
}
